//
//  EatClassPageSecondViewController.swift
//  01 联系
//
//  Created by 盈灿－刘鑫奇 on 16/2/16.
//  Copyright © 2016年 盈灿－刘鑫奇. All rights reserved.
//

import UIKit
import AVFoundation
import AVKit

class EatClassPageSecondViewController: UIViewController ,UICollectionViewDelegate,UICollectionViewDataSource,UITableViewDelegate,UITableViewDataSource,ReportUserDelegate,UIAlertViewDelegate{
    var bgScrollView : UIScrollView!
    var topView : UIView!
    
    var eatClassAVPlayerControl : AVPlayerViewController!
    var titleLabel : UILabel?//标题
    var detailLabel : UILabel?//介绍
    
    var eatClassCollectionView : UICollectionView!//集数
    var eatClassNumber : Int = -1 //记录点击视频的集数
    
    var eatClassNumberAll : Int = 16//视频集数
    var collectionViewHeight : CGFloat!
    var detailLabelHeight : CGFloat!

    var eatClassReviewTableView : UITableView!//评论tableView，我要评论为头视图
    
    
    var eatClassModel : EatClassPageModel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.whiteColor()
        
        
        eatClassNumber = eatClassModel.episode
        eatClassNumberAll = eatClassModel.episode_sum
        
        //计算collection，detail label高度
        let inta :Int = Int((UIScreen.mainScreen().bounds.width - 40) / 8)
         collectionViewHeight = CGFloat( (eatClassNumberAll / 8 + 1) * inta)
        let string: NSString = "afnwnv就啊神佛啊舒服绿那女 首脑 那淑女哦你说呢v 啊送 v 安思文哦你初三少女阿森纳VS女女怕v 呢afnwnv就啊神佛啊舒服绿那女 首脑 那淑女哦你说呢v 啊送 v 安思文哦你初三少女阿森纳VS女女怕v 呢"
        let fontDic: NSDictionary = NSDictionary(object: UIFont.systemFontOfSize(14), forKey: NSFontAttributeName)

        let boundingRect = string.boundingRectWithSize(CGSizeMake(UIScreen.mainScreen().bounds.width, 0), options:NSStringDrawingOptions.UsesLineFragmentOrigin , attributes: fontDic as? [String : AnyObject], context: nil)

        
        detailLabelHeight = boundingRect.height
        
        topView = UIView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, 260 + collectionViewHeight + detailLabelHeight))
        topView.backgroundColor = UIColor.whiteColor()
        
//        createTopView()
//        createCollectionView()
        createBottomView()
        
        createData()
        
        
        
        // Do any additional setup after loading the view.
    }
    //头视图
    func createTopView(){
        
        //计算顶部view高度

  //avpler
        let player = AVPlayer(URL: NSURL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")!)
//        let playerlayer = AVPlayerLayer(player: player)
        
        eatClassAVPlayerControl = AVPlayerViewController()
        eatClassAVPlayerControl.player = player
        self.addChildViewController(eatClassAVPlayerControl)
        eatClassAVPlayerControl.view.frame = CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, 200)
//        playerlayer.frame = eatClassAVPlayerControl.view.frame
//        eatClassAVPlayerControl.view.layer.addSublayer(playerlayer)
        self.topView.addSubview(eatClassAVPlayerControl.view)

        
        titleLabel = UILabel (frame: CGRectMake(20, 200, UIScreen.mainScreen().bounds.width - 20, 40))
        titleLabel?.font = UIFont.systemFontOfSize(15)
        titleLabel?.font = UIFont.boldSystemFontOfSize(16)
        titleLabel?.adjustsFontSizeToFitWidth = true
        titleLabel?.text = "啊哈哈哈哈啊哈哈哈哈"
        
        detailLabel = UILabel (frame: CGRectMake(20, (titleLabel?.frame.size.height)! + (titleLabel?.frame.origin.y)! , UIScreen.mainScreen().bounds.width - 40, detailLabelHeight))
        detailLabel?.font = UIFont.systemFontOfSize(14)
        detailLabel?.textColor = UIColor.lightGrayColor()
        detailLabel?.numberOfLines = 0
        detailLabel?.text =  "afnwnv就啊神佛啊舒服绿那女 首脑 那淑女哦你说呢v 啊送 v 安思文哦你初三少女阿森纳VS女女怕v 呢afnwnv就啊神佛啊舒服绿那女 首脑 那淑女哦你说呢v 啊送 v 安思文哦你初三少女阿森纳VS女女怕v呢"
        detailLabel!.lineBreakMode = NSLineBreakMode.ByWordWrapping


        self.topView.addSubview(titleLabel!)
        self.topView.addSubview(detailLabel!)
    }
    //集数
    func createCollectionView(){
        
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSizeMake((UIScreen.mainScreen().bounds.width - 40) / 9, (UIScreen.mainScreen().bounds.width - 40) / 9)
        
        eatClassCollectionView = UICollectionView(frame: CGRectMake(20, detailLabel!.frame.size.height + detailLabel!.frame.origin.y + 10, UIScreen.mainScreen().bounds.width - 40, collectionViewHeight), collectionViewLayout: flowLayout)
        
        self.topView.addSubview(eatClassCollectionView!)
        flowLayout.minimumLineSpacing = 5;
        flowLayout.minimumInteritemSpacing = 5
        
        eatClassCollectionView.delegate = self
        eatClassCollectionView.dataSource = self
        eatClassCollectionView.registerClass(EatClassSecondCollectionViewCell.self, forCellWithReuseIdentifier: "EatClassSecondCollectionViewCell")
        eatClassCollectionView.backgroundColor = UIColor.whiteColor()
        
        
        
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return eatClassNumberAll
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell :EatClassSecondCollectionViewCell? = (collectionView.dequeueReusableCellWithReuseIdentifier("EatClassSecondCollectionViewCell", forIndexPath: indexPath) as? EatClassSecondCollectionViewCell)
        cell!.eatClassNumberLabel.text = String(indexPath.row + 1)
        print(cell!.eatClassNumberLabel.text)
        if eatClassNumber == indexPath.row {
            cell?.backgroundColor = UIColor.orangeColor()
        }else{
            cell?.backgroundColor = UIColor(white: 0.8, alpha: 0.8)
        }
        return cell!
    }
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        print(indexPath.row)
        eatClassNumber = indexPath.row
        let avPlayer = AVPlayer(URL: NSURL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")!)
        eatClassAVPlayerControl.player = avPlayer
        
        detailLabel?.text = "点击了别的内容，播放不同视频"
        
        let fontDic: NSDictionary = NSDictionary(object: UIFont.systemFontOfSize(14), forKey: NSFontAttributeName)
        let boundingRect = detailLabel!.text!.boundingRectWithSize(CGSizeMake(UIScreen.mainScreen().bounds.width, 0), options:NSStringDrawingOptions.UsesLineFragmentOrigin , attributes: fontDic as? [String : AnyObject], context: nil)
        
        
        detailLabelHeight = boundingRect.height
        detailLabel!.frame = CGRectMake(20, (titleLabel?.frame.size.height)! + (titleLabel?.frame.origin.y)! , UIScreen.mainScreen().bounds.width - 40, detailLabelHeight)
        eatClassCollectionView!.frame = CGRectMake(20, detailLabel!.frame.size.height + detailLabel!.frame.origin.y + 10, UIScreen.mainScreen().bounds.width - 40, collectionViewHeight)
        
        topView = UIView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, 260 + collectionViewHeight + detailLabelHeight))
//        eatClassCollectionView .reloadData()
        eatClassReviewTableView.reloadData()
        
        
    }
    
    //底部评论
    func createBottomView() {
        
        eatClassReviewTableView = UITableView (frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height), style: UITableViewStyle.Grouped)
        eatClassReviewTableView.delegate = self
        eatClassReviewTableView.dataSource = self
     eatClassReviewTableView.registerNib(UINib(nibName:"EatClassSecondTableViewCell", bundle: nil),forCellReuseIdentifier:"eatClassSecondTableViewCell")

        eatClassReviewTableView.estimatedRowHeight = 40
        eatClassReviewTableView.rowHeight = UITableViewAutomaticDimension
        
        eatClassReviewTableView.backgroundColor = UIColor.whiteColor()
        self.view.addSubview(eatClassReviewTableView)
        
        eatClassReviewTableView.scrollsToTop = false

        
    }
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return topView.frame.size.height + 70
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier("eatClassSecondTableViewCell") as! EatClassSecondTableViewCell
        
        let arr = ["由盛EatClassSecondTableViewCell", "王EatClassSecondTableViewCellEatClassSecondTableViewCellEatClassSecondTableViewCell男", "余浩","由盛EatClassSecondTableViewCell", "王EatClassSecondTableViewCellEatClassSecondTableViewCellEatClassSecondTableViewCell男", "余浩","由盛EatClassSecondTableViewCell", "王EatClassSecondTableViewCellEatClassSecondTableViewCellEatClassSecondTableViewCell男", "余浩","asdfafas"]
        
        cell.userDetailLabel.text = arr[indexPath.row]
        cell.selectionStyle = UITableViewCellSelectionStyle.None
        cell.delegate = self
        cell.userReportButton.tag = 1000 + indexPath.row
        
        
        return cell
        
    }
    //评论头视图
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        createTopView()
        createCollectionView()
        
        let headerView = UIView (frame: CGRectMake(0, 0, eatClassReviewTableView.frame.size.width, 30 + topView.frame.height))
        headerView.backgroundColor = UIColor(white: 0.8, alpha: 0.5)
        self.topView.backgroundColor = UIColor.whiteColor()
        headerView.addSubview(self.topView)
        
        let headerViewbottom = UIView (frame: CGRectMake(0, self.topView.frame.height + 10, eatClassReviewTableView.frame.size.width, 60))
        headerViewbottom.backgroundColor = UIColor.whiteColor()
        
        let headerlabel = UILabel (frame: CGRectMake(20, 0, headerView.frame.size.width,20))
        headerlabel.text = "424523条评论"
        headerlabel.font = UIFont.systemFontOfSize(14)
        
        let headerButton = UIButton(frame: CGRectMake(20, headerlabel.frame.size.height + headerlabel.frame.origin.y, headerView.frame.size.width - 40, 30))
        headerButton.setTitle("我要评论", forState: UIControlState.Normal)
        headerButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        
        headerButton.backgroundColor = UIColor.orangeColor()
        headerButton.addTarget(self, action:Selector  ("myReporter"), forControlEvents: UIControlEvents.TouchUpInside)
        
        
        headerViewbottom.addSubview(headerlabel)
        headerViewbottom.addSubview(headerButton)
        
        headerView.addSubview(headerViewbottom)
        
        return headerView
    }
    
    //评论点击
    func myReporter() {
        print("我要评论")
    }
    
    //举报点击事件
    func reportLClick(number: Int) {
        
        print("点击了button,%d",number)
        
        let reportAlert = UIAlertController (title: "举报", message: nil, preferredStyle: UIAlertControllerStyle.Alert)
        
        reportAlert.addTextFieldWithConfigurationHandler { (textField:UITextField!) -> Void in
            textField.placeholder = "举报理由"
        }
        let okAction = UIAlertAction (title: "确定", style: UIAlertActionStyle.Default) { (action:UIAlertAction!) -> Void in
            print("queding")
        }
        let noAction = UIAlertAction (title: "取消", style: UIAlertActionStyle.Cancel) { (action:UIAlertAction!) -> Void in
            print("取消")
        }
        reportAlert.addAction(okAction)
        reportAlert.addAction(noAction)
        
        self.presentViewController(reportAlert, animated: true) { () -> Void in
            
        }
        
    }

    
    
    func createData(){
        
        let url: String = "http://h5.izhangchu.com/course/view.html?&series_id=" + String(eatClassModel.series_id) + "&episode=" + String(eatClassNumber)  + "&app_exitpage=1&from=app&"
        
        XRAFNetworkTool.GETUrl(url, body: nil, headFile: nil, response: XRResponseStyle.XRJSON, success: { (dataText, request) -> Void in
            
            print(request)
            
            
            }) { (dataText, request) -> Void in
                
        }
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
